<template>
    <div class="guestbook-page">
        <div class="guestbook-container">
            <!-- 留言表单 -->
            <div class="message-form cards">
                <h2>留言板</h2>
                <p class="subtitle">期待与你的交流~</p>
                <div class="form-group">
                    <input type="text" v-model="newMessage.nickname" placeholder="昵称" class="form-input">
                </div>
                <div class="form-group">
                    <input type="email" v-model="newMessage.email" placeholder="邮箱（选填）" class="form-input">
                </div>
                <div class="form-group">
                    <textarea v-model="newMessage.content" placeholder="说点什么吧..." class="form-textarea"></textarea>
                </div>
                <div class="form-footer">
                    <div class="emoji-picker">
                        <button class="emoji-btn" @click.stop="toggleEmojiPicker">
                            <svg class="icon" viewBox="0 0 1024 1024" width="24" height="24">
                                <path
                                    d="M512 832c-176.448 0-320-143.552-320-320S335.552 192 512 192s320 143.552 320 320-143.552 320-320 320m0-704c-211.744 0-384 172.256-384 384s172.256 384 384 384 384-172.256 384-384-172.256-384-384-384"
                                    fill="currentColor"></path>
                                <path
                                    d="M700.416 580.064c-11.264-3.744-23.936 2.368-27.616 13.696-0.192 0.576-21.376 57.408-160.8 57.408-139.616 0-160.544-56.832-160.736-57.408-3.68-11.328-16.352-17.44-27.616-13.696-11.264 3.744-17.312 16.256-13.632 27.584 1.344 4.032 33.824 98.144 202.048 98.144s200.704-94.112 202.048-98.144c3.68-11.328-2.432-23.84-13.696-27.584M368 432a48 48 0 1 0 96 0 48 48 0 1 0-96 0ZM560 432a48 48 0 1 0 96 0 48 48 0 1 0-96 0Z"
                                    fill="currentColor"></path>
                            </svg>
                        </button>
                        <div v-if="showEmojiPicker" class="emoji-panel">
                            <span v-for="emoji in emojiList" :key="emoji" @click="insertEmoji(emoji)"
                                class="emoji-item">
                                {{ emoji }}
                            </span>
                        </div>
                    </div>
                    <button @click="submitMessage" class="submit-btn">
                        <svg class="icon" viewBox="0 0 1024 1024" width="16" height="16">
                            <path
                                d="M931.4 498.9L94.9 79.5c-3.4-1.7-7.3-2.1-11-1.2-8.5 2.1-13.8 10.7-11.7 19.3l86.2 352.2c1.3 5.3 5.2 9.6 10.4 11.3l147.7 50.7-147.6 50.7c-5.2 1.8-9.1 6-10.3 11.3L72.2 926.5c-0.9 3.7-0.5 7.6 1.2 10.9 3.9 7.9 13.5 11.1 21.5 7.2l836.5-417c3.1-1.5 5.6-4.1 7.2-7.1 3.9-8 0.7-17.6-7.2-21.6zM170.8 826.3l50.3-205.6 295.2-101.3c2.3-0.8 4.2-2.6 5-5 1.4-4.2-0.8-8.7-5-10.2L221.1 403 171 198.2l628 314.9-628.2 313.2z"
                                fill="currentColor"></path>
                        </svg>
                        发送留言
                    </button>
                </div>
            </div>

            <!-- 留言列表 -->
            <div class="message-list">
                <div v-for="message in messages" :key="message.id" class="message-item cards">
                    <div class="message-header">
                        <div class="user-info">
                            <div class="avatar">
                                <!-- 使用默认头像或gravatar -->
                                <img :src="getAvatar(message.email, message.nickname, message.id)" alt="avatar">
                            </div>
                            <div class="info-detail">
                                <span class="nickname">{{ message.nickname }}</span>
                                <span class="time">{{ formatTime(message.createTime) }}</span>
                            </div>
                        </div>
                        <div class="message-actions">
                            <button @click="handleLike(message)" class="action-btn">
                                <svg class="icon" viewBox="0 0 1024 1024" width="16" height="16"
                                    :class="{ 'liked': message.isLiked }">
                                    <path
                                        d="M512 896a42.666667 42.666667 0 0 1-30.293333-12.373333l-331.52-331.52c-70.912-69.973333-78.506667-180.906667-17.066667-260.693334 35.84-46.506667 89.6-72.746667 147.626667-72.746666 57.173333 0 110.933333 26.24 147.626666 72.746666L512 376.32l83.626667-84.906667c36.693333-46.506667 90.453333-72.746667 147.626666-72.746666 58.026667 0 111.786667 26.24 147.626667 72.746666 61.44 79.786667 53.845333 190.72-17.066667 260.693334l-331.52 331.52A42.666667 42.666667 0 0 1 512 896z"
                                        fill="currentColor"></path>
                                </svg>
                                <span>{{ message.likes || 0 }}</span>
                            </button>
                            <button @click="replyTo(message)" class="action-btn">
                                <svg class="icon" viewBox="0 0 1024 1024" width="16" height="16">
                                    <path
                                        d="M789.333333 832a42.666667 42.666667 0 0 1-30.293333-12.373333L640 700.586667V789.333333a42.666667 42.666667 0 0 1-42.666667 42.666667H170.666667a42.666667 42.666667 0 0 1-42.666667-42.666667V234.666667a42.666667 42.666667 0 0 1 42.666667-42.666667h426.666666a42.666667 42.666667 0 0 1 42.666667 42.666667v88.746666l119.04-119.04a42.666667 42.666667 0 0 1 60.586667 0l170.666666 170.666667a42.666667 42.666667 0 0 1 0 60.586667l-170.666666 170.666666a42.666667 42.666667 0 0 1-30.293334 12.373334z"
                                        fill="currentColor"></path>
                                </svg>
                                回复
                            </button>
                        </div>
                    </div>
                    <div class="message-content">{{ message.content }}</div>

                    <!-- 回复框 -->
                    <div v-if="replyingTo === message.id" class="reply-form">
                        <div class="form-group">
                            <input type="text" v-model="replyMessage.nickname" placeholder="昵称" class="form-input">
                        </div>
                        <div class="form-group">
                            <textarea v-model="replyMessage.content" placeholder="回复内容..."
                                class="form-textarea"></textarea>
                        </div>
                        <div class="form-footer">
                            <button @click="cancelReply" class="cancel-btn">取消</button>
                            <button @click="submitReply(message)" class="submit-btn">回复</button>
                        </div>
                    </div>

                    <!-- 回复列表 -->
                    <div v-if="message.replies && message.replies.length" class="reply-list">
                        <div v-for="reply in message.replies" :key="reply.id" class="reply-item">
                            <div class="reply-header">
                                <div class="user-info">
                                    <div class="avatar">
                                        <img :src="getAvatar(reply.email, reply.nickname, reply.id)" alt="avatar">
                                    </div>
                                    <div class="info-detail">
                                        <span class="nickname">{{ reply.nickname }}</span>
                                        <span class="time">{{ formatTime(reply.createTime) }}</span>
                                    </div>
                                </div>
                            </div>
                            <div class="reply-content">{{ reply.content }}</div>
                        </div>
                    </div>
                </div>

                <!-- 加载更多 -->
                <div v-if="hasMore" class="load-more">
                    <button @click="loadMore" class="load-more-btn">
                        <i class="iconfont icon-loading" :class="{ 'loading': isLoading }"></i>
                        加载更多
                    </button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import type { Message, NewMessage, Reply } from '@/types/guestbook'
import md5 from 'md5'
import { formatDistanceToNow } from 'date-fns'
import { zhCN } from 'date-fns/locale'
import { getMessages, createMessage, replyMessage as replyMessageApi, likeMessage as likeMessageApi } from '@/api/guestbook'

// 表情列表
const emojiList = [
    '😊', '', '🤔', '👍', '❤️', '😎', '🎉', '🤗', '😄', '🥳',
    '😅', '😉', '😋', '😍', '😘', '🤩', '🥰', '😇', '😌', '😏',
    '👋', '🎵', '🌈', '✨', '💫', '💖', '💝', '💕', '💞', '💓',
    '🤝', '🙏', '🌸', '🍀', '🌺', '🌼', '🌻', '🌹', '🍓', '🍰',
    '😁', '🥺', '🤪', '😜', '😝', '😛', '😚', '😙', '🥲', '☺️',
    '🤭', '🤫', '🤥', '😶', '😐', '😑', '😬', '🙄', '😯', '😦',
    '🌟', '🎨', '🎭', '🎪', '🎢', '🎡', '🎠', '🎮', '🎲', '🎯',
    '🦋', '🐛', '🐝', '🐞', '🐌', '🦗', '🦂', '🕷️', '🕸️', '🌱'
]
const showEmojiPicker = ref(false)

const replyingTo = ref<number | null>(null)
const replyMessage = ref<NewMessage>({
    nickname: '',
    email: '',
    content: ''
})

const newMessage = ref<NewMessage>({
    nickname: '',
    email: '',
    content: ''
})

const messages = ref<Message[]>([])
const page = ref(1)
const pageSize = ref(10)
const hasMore = ref(true)
const isLoading = ref(false)

// 添加一个 Map 来存储用户的随机种子
const userAvatarSeeds = new Map<string, string>()

// 修改 getAvatar 方法
const getAvatar = (email: string | null, nickname: string, id?: number) => {
    // 如果是管理员邮箱，使用固定头像
    if (email === '2416018692@qq.com') {
        return 'https://api.dicebear.com/7.x/miniavs/svg?seed=admin&backgroundColor=ffdfbf&scale=90'  // 使用固定的管理员头像
    }

    // 为其他用户生成固定的随机头像
    const styles = ['adventurer', 'avataaars', 'bottts', 'micah']

    // 使用 id + nickname 作为唯一标识
    const seed = `${id || ''}${nickname}`

    // 使用固定的种子来选择风格
    const styleIndex = Math.abs(seed.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0)) % styles.length
    const style = styles[styleIndex]

    return `https://api.dicebear.com/7.x/${style}/svg?seed=${seed}&backgroundColor=transparent`
}

// 格式化时间
const formatTime = (time: string | undefined) => {
    if (!time) return ''
    return formatDistanceToNow(new Date(time), { addSuffix: true, locale: zhCN })
}

// 切换表情面板
const toggleEmojiPicker = () => {
    showEmojiPicker.value = !showEmojiPicker.value
}

// 插入表情
const insertEmoji = (emoji: string) => {
    newMessage.value.content += emoji
    // 插入表情后关闭面板
    showEmojiPicker.value = false
}

// 添加点击外部关闭表情面板的功能
const closeEmojiPicker = (event: MouseEvent) => {
    const target = event.target as HTMLElement
    const picker = document.querySelector('.emoji-picker')
    if (picker && !picker.contains(target)) {
        showEmojiPicker.value = false
    }
}

// 在组件挂载时添加点击事件监听
onMounted(() => {
    document.addEventListener('click', closeEmojiPicker)
})

// 在组件卸载时移除事件监听
onUnmounted(() => {
    document.removeEventListener('click', closeEmojiPicker)
})

// 点赞功能
const handleLike = async (message: Message) => {
    try {
        const { likes, isLiked } = await likeMessageApi(message.id)
        message.likes = likes
        message.isLiked = isLiked
    } catch (error) {
        console.error('点赞失败:', error)
        alert('点赞失败，请稍后重试')
    }
}

// 回复功能
const replyTo = (message: any) => {
    replyingTo.value = message.id
    replyMessage.value = {
        nickname: '',
        email: '',
        content: ''
    }
}

const cancelReply = () => {
    replyingTo.value = null
}

const submitReply = async (message: Message) => {
    if (!replyMessage.value.nickname || !replyMessage.value.content) {
        alert('请填写昵称和回复内容')
        return
    }

    try {
        const updatedMessage = await replyMessageApi({
            messageId: message.id,
            nickname: replyMessage.value.nickname,
            email: replyMessage.value.email,
            content: replyMessage.value.content
        })

        // 更新当前留言的回复列表
        const index = messages.value.findIndex(m => m.id === message.id)
        if (index !== -1) {
            // 确保回复列表存在
            if (!updatedMessage.replies) {
                updatedMessage.replies = []
            }

            // 对回复进行排序，Admin的回复放在最上面
            updatedMessage.replies.sort((a, b) => {
                if (a.nickname === 'Admin') return -1
                if (b.nickname === 'Admin') return 1
                return new Date(b.createTime).getTime() - new Date(a.createTime).getTime()
            })

            messages.value[index] = updatedMessage
        }

        // 清空回复表单
        replyMessage.value = {
            nickname: '',
            email: '',
            content: ''
        }
        replyingTo.value = null
    } catch (error) {
        console.error('提交回复失败:', error)
        alert('提交回复失败，请稍后重试')
    }
}

// 加载更多
const loadMore = async () => {
    if (isLoading.value) return
    isLoading.value = true

    try {
        const res = await getMessages({
            page: page.value + 1,
            pageSize: pageSize.value
        })

        if (res && res.list) {
            const newMessages = res.list.map(message => {
                const replies = Array.isArray(message.replies) ? message.replies : []

                // 对回复进行排序，Admin的回复放在最上面
                replies.sort((a, b) => {
                    if (a.nickname === 'Admin') return -1
                    if (b.nickname === 'Admin') return 1
                    return new Date(b.createTime).getTime() - new Date(a.createTime).getTime()
                })

                return {
                    ...message,
                    replies,
                    likedIps: Array.isArray(message.likedIps) ? message.likedIps : [],
                    likes: message.likes || 0,
                    isLiked: false
                }
            })
            messages.value.push(...newMessages)
            hasMore.value = res.hasMore
            page.value++
        }
    } catch (error) {
        console.error('加载留言失败:', error)
        alert('加载失败，请稍后重试')
    } finally {
        isLoading.value = false
    }
}

// 初始化加载留言
onMounted(async () => {
    try {
        const res = await getMessages({
            page: 1,
            pageSize: pageSize.value
        })
        console.log('留言列表数据:', res)
        if (res && res.list) {
            // 确保每个留言对象都有必要的属性，并对回复进行排序
            messages.value = res.list.map(message => {
                const replies = Array.isArray(message.replies) ? message.replies : []

                // 对回复进行排序，Admin的回复放在最上面
                replies.sort((a, b) => {
                    if (a.nickname === 'Admin') return -1
                    if (b.nickname === 'Admin') return 1
                    return new Date(b.createTime).getTime() - new Date(a.createTime).getTime()
                })

                return {
                    ...message,
                    replies,
                    likedIps: Array.isArray(message.likedIps) ? message.likedIps : [],
                    likes: message.likes || 0,
                    isLiked: false
                }
            })
            hasMore.value = res.hasMore
        }
    } catch (error) {
        console.error('加载留言失败:', error)
        alert('加载失败，请稍后重试')
    }
})

const submitMessage = async () => {
    if (!newMessage.value.nickname || !newMessage.value.content) {
        alert('请填写昵称和留言内容')
        return
    }

    try {
        const message = await createMessage(newMessage.value)
        messages.value.unshift(message)

        // 清空表单
        newMessage.value = {
            nickname: '',
            email: '',
            content: ''
        }
    } catch (error) {
        console.error('提交留言失败:', error)
        alert('提交留言失败，请稍后重试')
    }
}
</script>

<style scoped>
.guestbook-page {
    min-height: 100vh;
    padding: 2rem 1rem;
    background: linear-gradient(135deg, #1f1f1f 0%, #111 100%);
    position: relative;
    overflow: auto;
}

/* 添动态背景效果 */
.guestbook-page::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background:
        radial-gradient(circle at 20% 30%, rgba(41, 196, 255, 0.1) 0%, transparent 50%),
        radial-gradient(circle at 80% 70%, rgba(255, 41, 111, 0.1) 0%, transparent 50%);
    pointer-events: none;
}

.guestbook-container {
    position: relative;
    z-index: 1;
    max-width: 800px;
    margin: 0 auto;
    display: flex;
    flex-direction: column;
    gap: 2rem;
}

.cards {
    padding: 2rem;
    color: #fff;
    background: rgba(255, 255, 255, 0.05);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 16px;
    box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
}

.cards:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 40px rgba(0, 0, 0, 0.2);
    border-color: rgba(255, 255, 255, 0.2);
}

.message-form {
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.1) 0%, rgba(255, 255, 255, 0.05) 100%);
}

.message-form h2 {
    font-size: 1.5rem;
    margin-bottom: 0.5rem;
}

.subtitle {
    color: rgba(255, 255, 255, 0.8);
    margin-bottom: 1.5rem;
}

.form-group {
    margin-bottom: 1rem;
}

.form-input,
.form-textarea {
    width: 100%;
    padding: 0.75rem;
    background: rgba(0, 0, 0, 0.2);
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 8px;
    color: #fff;
    transition: all 0.3s ease;
}

.form-input:focus,
.form-textarea:focus {
    outline: none;
    border-color: rgba(255, 255, 255, 0.3);
    background: rgba(0, 0, 0, 0.3);
    box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.1);
}

.form-textarea {
    min-height: 120px;
    resize: vertical;
}

.submit-btn {
    background: linear-gradient(135deg, #29c4ff 0%, #2979ff 100%);
    border: none;
    padding: 0.75rem 2rem;
    border-radius: 8px;
    color: #fff;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}

.submit-btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 20px rgba(41, 196, 255, 0.4);
}

.message-list {
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

.message-item {
    padding: 1.5rem;
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.08) 0%, rgba(255, 255, 255, 0.03) 100%);
    animation: fadeIn 0.5s ease forwards;
}

.message-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1rem;
}

.user-info {
    display: flex;
    align-items: center;
    gap: 1rem;
}

.nickname {
    font-weight: bold;
}

.time {
    font-size: 0.9rem;
    opacity: 0.6;
}

.action-btn {
    padding: 0.25rem 0.75rem;
    background: rgba(255, 255, 255, 0.1);
    border: none;
    border-radius: 4px;
    color: #fff;
    cursor: pointer;
    transition: all 0.3s ease;
}

.action-btn:hover {
    background: rgba(255, 255, 255, 0.2);
}

.message-content {
    line-height: 1.6;
    margin-bottom: 1rem;
}

.reply-list {
    margin-left: 2rem;
    padding-left: 1rem;
    border-left: 2px solid rgba(255, 255, 255, 0.1);
}

.reply-item {
    background: rgba(0, 0, 0, 0.2);
    border-radius: 8px;
    margin-top: 1rem;
    padding: 1rem;
    transition: all 0.3s ease;
}

.reply-item:hover {
    background: rgba(0, 0, 0, 0.3);
}

.reply-header {
    display: flex;
    align-items: center;
    gap: 1rem;
    margin-bottom: 0.5rem;
}

.reply-content {
    line-height: 1.6;
}

/* 移动端适配 */
@media (max-width: 768px) {
    .guestbook-page {
        padding: 1rem;
    }

    .cards {
        padding: 1.5rem;
    }

    .message-form h2 {
        font-size: 1.25rem;
    }

    .reply-list {
        margin-left: 1rem;
    }
}

.avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    overflow: hidden;
}

.avatar img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.info-detail {
    display: flex;
    flex-direction: column;
    gap: 0.25rem;
}

.form-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 1rem;
}

.emoji-picker {
    position: relative;
    z-index: 10;
}

.emoji-btn {
    padding: 8px;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 8px;
    border: 1px solid rgba(255, 255, 255, 0.1);
    color: #fff;
    cursor: pointer;
    transition: all 0.3s ease;
}

.emoji-btn:hover {
    background: rgba(255, 255, 255, 0.2);
}

.emoji-panel {
    position: absolute;
    bottom: 100%;
    left: 0;
    background: rgba(30, 30, 30, 0.95);
    backdrop-filter: blur(10px);
    padding: 12px;
    border-radius: 8px;
    border: 1px solid rgba(255, 255, 255, 0.1);
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
    display: grid;
    grid-template-columns: repeat(8, 1fr);
    gap: 8px;
    margin-bottom: 8px;
    min-width: 320px;
    max-height: 300px;
    overflow-y: auto;
}

.emoji-panel::-webkit-scrollbar {
    width: 6px;
}

.emoji-panel::-webkit-scrollbar-track {
    background: rgba(0, 0, 0, 0.1);
    border-radius: 3px;
}

.emoji-panel::-webkit-scrollbar-thumb {
    background: rgba(255, 255, 255, 0.2);
    border-radius: 3px;
}

.emoji-panel::-webkit-scrollbar-thumb:hover {
    background: rgba(255, 255, 255, 0.3);
}

.emoji-item {
    cursor: pointer;
    padding: 6px;
    font-size: 20px;
    text-align: center;
    border-radius: 4px;
    transition: all 0.2s ease;
    user-select: none;
}

.emoji-item:hover {
    background: rgba(255, 255, 255, 0.1);
    transform: scale(1.2);
}

.liked {
    color: #ff4b4b;
}

.load-more {
    text-align: center;
    margin-top: 2rem;
}

.load-more-btn {
    padding: 0.75rem 2rem;
    background: rgba(255, 255, 255, 0.1);
    border: none;
    border-radius: 4px;
    color: #fff;
    cursor: pointer;
    transition: all 0.3s ease;
}

.load-more-btn:hover {
    background: rgba(255, 255, 255, 0.2);
}

.loading {
    animation: spin 1s linear infinite;
}

@keyframes spin {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(360deg);
    }
}

.cancel-btn {
    padding: 0.75rem 2rem;
    background: rgba(255, 255, 255, 0.1);
    border: none;
    border-radius: 4px;
    color: #fff;
    cursor: pointer;
    margin-right: 1rem;
}

.user-info {
    display: flex;
    gap: 1rem;
    align-items: center;
}

/* 适配移动端的补充样式 */
@media (max-width: 768px) {
    .form-footer {
        flex-direction: column;
        gap: 1rem;
        align-items: stretch;
    }

    .emoji-panel {
        position: fixed;
        left: 16px;
        right: 16px;
        bottom: 80px;
        min-width: auto;
        max-height: 40vh;
        grid-template-columns: repeat(6, 1fr);
    }
}

/* 添加动画效果 */
@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(20px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.message-item {
    animation: fadeIn 0.5s ease forwards;
}

/* 图标样式 */
.icon {
    vertical-align: middle;
    margin-right: 4px;
}

/* 按钮图标通用样式 */
.action-btn .icon {
    transition: transform 0.2s ease;
}

.action-btn:hover .icon {
    transform: scale(1.1);
}

/* 发送按钮样式优化 */
.submit-btn {
    display: inline-flex;
    align-items: center;
    gap: 6px;
}

.submit-btn .icon {
    margin: 0;
}
</style>